package practice;

import java.util.Arrays;

/**
 * Created by 蜡笔小新丶 on 2017/9/22.
 */
public class  Bag <T> implements BagInterface<T>{
    Object bags1[],bags2[];
    public <T> Bag(){
        bags1 = new Object[10];
    }
    public boolean isEmptey(){
        boolean result = false;
        int num = 0;
        for(int i = 0; i< bags1.length ; i++)
            if(bags1[i]==null)
                num++;
        if(num == bags1.length)
            result = true;
        return result;
    }

    private boolean isfull(T arr[]){
        boolean result = false;
        int num = arr.length;
        for(int i=0;i<arr.length;i++){
            if (arr[i]==null)
                num = arr.length-1;
        }
        if(num==arr.length)
            result = true;
        return result;
    }

    private int emptey(T arr[]){
        int i=0;
        while (true){
            if(arr[i]==null)
                break;
            i++;
        }
        return i;
    }

    private Object[] become(T[] arr){
        bags2 = new Object[arr.length+10];
        for(int i=0;i<arr.length;i++){
            bags2[i]=arr[i];
        }
        return bags2;
    }

    @Override
    public boolean add(T thing) {
        if(isfull((T[]) bags1)){
            bags1 = (T[]) become((T[]) bags1);
            bags1[emptey((T[]) bags1)]=  thing;
        }else
            bags1[emptey((T[]) bags1)]= thing;
        return true;
    }

    public void remove(T thing){
        int result[] = new int[bags1.length];
        int j = 0;
        for(int i = 0; i< bags1.length; i++){
            if(bags1[i]!=null)
                if(bags1[i].equals(thing)){
                    result[j] = i+1;
                    j++;
                }
        }
        for(int i=0;result[i]!=0;i++)
            bags1[result[i]-1] = null;
    }

    @Override
    public String toString() {
        return "Bag{" +
                "bags1=" + Arrays.toString(bags1) +
                '}';
    }
}